package handler

import (
	"github.com/gin-gonic/gin"
	"me/123/api/client"
	"me/123/api/enit/request"
	"me/123/api/enit/response"
	"me/123/common/proto/order"
	"strconv"
)

func OrderCreate(c *gin.Context) {
	var req request.OrderCreate

	if err := c.ShouldBind(&req); err != nil {
		response.ErrorResponse(c, "参数错误", err.Error())
		return
	}

	userId := c.GetUint("userId")
	create, err := client.OrderCreate(c, &order.OrderCreateRequest{
		UserId:     int64(userId),
		ProductsId: req.ProductsId,
		Num:        req.Num,
		CouponsId:  req.CouponsId,
	})
	if err != nil {
		response.ErrorResponse(c, "err", err.Error())
		return
	}
	response.SuccessResponse(c, "ok", create)
}

func Callback(c *gin.Context) {
	sn := c.PostForm("out_trade_no")
	sta := c.PostForm("trade_status")

	if sta == "TRADE_FINISHED" {
		sta = "1"
	}
	if sta == "TRADE_SUCCESS" {
		sta = "2"
	}
	if sta == "WAIT_BUYER_PAY" {
		sta = "3"
	}
	if sta == "TRADE_CLOSED" {
		sta = "4"
	}

	status, _ := strconv.Atoi(sta)
	orderStatus, err := client.UpdateOrderStatus(c, &order.UpdateOrderStatusRequest{
		OrderSn:     sn,
		OrderStatus: int64(status),
	})
	if err != nil {
		response.ErrorResponse(c, "err", err.Error())
		return
	}
	response.SuccessResponse(c, "ok", orderStatus)
}
